#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>

using namespace std;
#define PTHREAD_NUM 5 // 线程数量
int tickets = 1000;   // 共享资源
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

struct ThreadData
{
    ThreadData(const string &name, pthread_mutex_t *pmutex)
        : _name(name), _pmutex(pmutex)
    {
    }

    string _name;
    pthread_mutex_t * _pmutex;
};

void* pthread_Fun(void *args)
{
    ThreadData *td = (ThreadData *)args;
    while (true)
    {
        pthread_mutex_lock(td->_pmutex);
        if (tickets > 0)
        {
            usleep(rand() % 1500);
            printf("%s, %p: %d\n", td->_name.c_str(), pthread_self(), tickets--);
            pthread_mutex_unlock(td->_pmutex);
        }
        else
        {
            pthread_mutex_unlock(td->_pmutex);
            printf("no tickets, %s, %p quit!\n", td->_name.c_str(), pthread_self());
            break;
        }
    }
    delete td;
    return nullptr;
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid());

    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    pthread_t tid[PTHREAD_NUM];
    for (int i = 0; i < PTHREAD_NUM; ++i)
    {
        string name="pthrad-";
        name+=to_string(1+i);
        ThreadData *td = new ThreadData(name,&mutex);
        cout << "create a new pthread: " << name << endl;
        pthread_create(tid + i, nullptr, pthread_Fun, (void *)td);
    }

    for (int i = 0; i < PTHREAD_NUM; ++i)
    {
        pthread_join(tid[i], nullptr);
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}